import { Platform, PermissionsAndroid, NativeModules } from 'react-native';
import { PERMISSIONS_CONFIG } from '../utils/constants';

class PermissionManager {
  constructor() {
    this.permissionStatus = {};
  }

  /**
   * 检查所有必需的权限
   */
  static async checkAllPermissions() {
    const results = {};
    
    // Android权限检查
    if (Platform.OS === 'android') {
      const androidPermissions = [
        PermissionsAndroid.PERMISSIONS.SYSTEM_ALERT_WINDOW,
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
      ];

      // Android 10+需要额外的后台位置权限
      if (Platform.Version >= 29) {
        androidPermissions.push(PermissionsAndroid.PERMISSIONS.ACCESS_BACKGROUND_LOCATION);
      }

      for (const permission of androidPermissions) {
        try {
          const granted = await PermissionsAndroid.check(permission);
          results[permission] = granted ? 'granted' : 'denied';
        } catch (error) {
          console.error(`检查权限失败: ${permission}`, error);
          results[permission] = 'error';
        }
      }
    }

    // 无障碍服务权限（需要原生模块支持）
    try {
      const accessibilityGranted = await this.checkAccessibilityPermission();
      results.accessibility = accessibilityGranted ? 'granted' : 'denied';
    } catch (error) {
      console.error('检查无障碍服务权限失败:', error);
      results.accessibility = 'error';
    }

    console.log('权限检查结果:', results);
    return results;
  }

  /**
   * 请求所有必需的权限
   */
  static async requestAllPermissions() {
    const results = {};
    
    // Android权限请求
    if (Platform.OS === 'android') {
      const androidPermissions = [
        {
          permission: PermissionsAndroid.PERMISSIONS.SYSTEM_ALERT_WINDOW,
          title: '悬浮窗权限',
          message: '应用需要悬浮窗权限来显示控制按钮',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定'
        },
        {
          permission: PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          title: '存储权限',
          message: '应用需要存储权限来保存配置和使用记录',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定'
        },
        {
          permission: PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
          title: '读取存储权限',
          message: '应用需要读取存储权限来访问视频文件',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定'
        }
      ];

      // Android 10+需要额外的后台位置权限
      if (Platform.Version >= 29) {
        androidPermissions.push({
          permission: PermissionsAndroid.PERMISSIONS.ACCESS_BACKGROUND_LOCATION,
          title: '后台位置权限',
          message: '应用需要后台位置权限来在后台运行',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定'
        });
      }

      for (const permissionConfig of androidPermissions) {
        try {
          const granted = await PermissionsAndroid.request(
            permissionConfig.permission,
            {
              title: permissionConfig.title,
              message: permissionConfig.message,
              buttonNeutral: permissionConfig.buttonNeutral,
              buttonNegative: permissionConfig.buttonNegative,
              buttonPositive: permissionConfig.buttonPositive,
            }
          );
          
          results[permissionConfig.permission] = granted === PermissionsAndroid.RESULTS.GRANTED ? 'granted' : 'denied';
        } catch (error) {
          console.error(`请求权限失败: ${permissionConfig.permission}`, error);
          results[permissionConfig.permission] = 'error';
        }
      }
    }

    // 请求无障碍服务权限
    try {
      const accessibilityGranted = await this.requestAccessibilityPermission();
      results.accessibility = accessibilityGranted ? 'granted' : 'denied';
    } catch (error) {
      console.error('请求无障碍服务权限失败:', error);
      results.accessibility = 'error';
    }

    console.log('权限请求结果:', results);
    return results;
  }

  /**
   * 检查无障碍服务权限
   */
  static async checkAccessibilityPermission() {
    try {
      if (NativeModules.AccessibilityService) {
        return await NativeModules.AccessibilityService.isEnabled();
      } else {
        console.warn('AccessibilityService原生模块未找到');
        return true; // 如果没有原生模块，默认返回true
      }
    } catch (error) {
      console.error('检查无障碍服务权限失败:', error);
      return false;
    }
  }

  /**
   * 请求无障碍服务权限
   */
  static async requestAccessibilityPermission() {
    try {
      if (NativeModules.AccessibilityService) {
        return await NativeModules.AccessibilityService.requestPermission();
      } else {
        console.warn('AccessibilityService原生模块未找到');
        return true; // 如果没有原生模块，默认返回true
      }
    } catch (error) {
      console.error('请求无障碍服务权限失败:', error);
      return false;
    }
  }

  /**
   * 检查悬浮窗权限
   */
  static async checkOverlayPermission() {
    if (Platform.OS !== 'android') return true;
    
    try {
      if (NativeModules.OverlayPermission) {
        return await NativeModules.OverlayPermission.canDrawOverlays();
      } else {
        console.warn('OverlayPermission原生模块未找到');
        return true; // 如果没有原生模块，默认返回true
      }
    } catch (error) {
      console.error('检查悬浮窗权限失败:', error);
      return false;
    }
  }

  /**
   * 请求悬浮窗权限
   */
  static async requestOverlayPermission() {
    if (Platform.OS !== 'android') return true;
    
    try {
      if (NativeModules.OverlayPermission) {
        return await NativeModules.OverlayPermission.requestPermission();
      } else {
        console.warn('OverlayPermission原生模块未找到');
        return true; // 如果没有原生模块，默认返回true
      }
    } catch (error) {
      console.error('请求悬浮窗权限失败:', error);
      return false;
    }
  }

  /**
   * 检查存储权限
   */
  static async checkStoragePermission() {
    if (Platform.OS !== 'android') return true;
    
    try {
      const writeGranted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
      const readGranted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
      
      return writeGranted && readGranted;
    } catch (error) {
      console.error('检查存储权限失败:', error);
      return false;
    }
  }

  /**
   * 请求存储权限
   */
  static async requestStoragePermission() {
    if (Platform.OS !== 'android') return true;
    
    try {
      const writeGranted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: '存储权限',
          message: '应用需要存储权限来保存配置和使用记录',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定',
        }
      );
      
      const readGranted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        {
          title: '读取存储权限',
          message: '应用需要读取存储权限来访问视频文件',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定',
        }
      );
      
      return writeGranted === PermissionsAndroid.RESULTS.GRANTED && 
             readGranted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (error) {
      console.error('请求存储权限失败:', error);
      return false;
    }
  }

  /**
   * 检查所有权限是否都已授予
   */
  static areAllPermissionsGranted(permissionResults) {
    const requiredPermissions = [
      'accessibility',
      PermissionsAndroid.PERMISSIONS.SYSTEM_ALERT_WINDOW,
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
    ];

    return requiredPermissions.every(permission => {
      const status = permissionResults[permission];
      return status === 'granted';
    });
  }

  /**
   * 获取缺失的权限列表
   */
  static getMissingPermissions(permissionResults) {
    const requiredPermissions = [
      { key: 'accessibility', name: '无障碍服务权限' },
      { key: PermissionsAndroid.PERMISSIONS.SYSTEM_ALERT_WINDOW, name: '悬浮窗权限' },
      { key: PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, name: '存储权限' },
      { key: PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, name: '读取存储权限' }
    ];

    return requiredPermissions
      .filter(permission => permissionResults[permission.key] !== 'granted')
      .map(permission => permission.name);
  }

  /**
   * 打开应用设置页面
   */
  static async openAppSettings() {
    try {
      if (NativeModules.SettingsOpener) {
        return await NativeModules.SettingsOpener.openAppSettings();
      } else {
        console.warn('SettingsOpener原生模块未找到');
        return false;
      }
    } catch (error) {
      console.error('打开应用设置失败:', error);
      return false;
    }
  }

  /**
   * 打开无障碍服务设置
   */
  static async openAccessibilitySettings() {
    try {
      if (NativeModules.AccessibilityService) {
        return await NativeModules.AccessibilityService.openSettings();
      } else {
        console.warn('AccessibilityService原生模块未找到');
        return false;
      }
    } catch (error) {
      console.error('打开无障碍服务设置失败:', error);
      return false;
    }
  }

  /**
   * 打开悬浮窗权限设置
   */
  static async openOverlaySettings() {
    try {
      if (NativeModules.OverlayPermission) {
        return await NativeModules.OverlayPermission.openSettings();
      } else {
        console.warn('OverlayPermission原生模块未找到');
        return false;
      }
    } catch (error) {
      console.error('打开悬浮窗权限设置失败:', error);
      return false;
    }
  }

  /**
   * 显示权限请求对话框
   */
  static async showPermissionDialog(permissions) {
    const missingPermissions = this.getMissingPermissions(permissions);
    
    if (missingPermissions.length === 0) {
      return true;
    }

    const permissionNames = missingPermissions.join('、');
    const message = `应用需要以下权限才能正常运行：\n\n${permissionNames}\n\n请在设置中授予这些权限。`;

    // 这里可以集成一个自定义的对话框组件
    console.log('权限请求信息:', message);
    
    return new Promise((resolve) => {
      // 模拟用户确认
      setTimeout(() => {
        resolve(true);
      }, 1000);
    });
  }
}

export default PermissionManager;